package tools

import (
	"fmt"
	"os"
	"os/exec"
	"regexp"
	"strings"
)

type Tools struct {
}

func NewTools() *Tools {
	return &Tools{}
}

func (t *Tools) Capitalize(str string) string {
	var upperStr string
	vv := []rune(str)
	for i := 0; i < len(vv); i++ {
		if i == 0 {
			if vv[i] >= 97 && vv[i] <= 122 {
				vv[i] -= 32
				upperStr += string(vv[i])
			} else {
				fmt.Println("Not begins with lowercase letter,")
				return str
			}
		} else {
			upperStr += string(vv[i])
		}
	}
	return upperStr
}

func (t *Tools) Lower(s string) string {
	if len(s) > 0 {
		return strings.ToLower(string(s[0])) + s[1:]
	}
	return s
}

func (t *Tools) Exists(path string) bool {
	_, err := os.Stat(path)
	if os.IsNotExist(err) {
		return false
	}
	return true
}

func (t *Tools) ToSnake(str string) string {
	str = regexp.MustCompile(`[^a-zA-Z0-9]+`).ReplaceAllString(str, "_")                 //非常规字符转化为 _
	snake := regexp.MustCompile("(.)([A-Z][a-z]+)").ReplaceAllString(str, "${1}_${2}")   //拆分出连续大写
	snake = regexp.MustCompile("([a-z0-9])([A-Z])").ReplaceAllString(snake, "${1}_${2}") //拆分单词
	return strings.ToLower(snake)                                                        //全部转小写
}

func (t *Tools) CommandLine(dir string, name string, args ...string) {
	cmd := exec.Command(name, args...)
	cmd.Dir = dir
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	if err := cmd.Run(); err != nil {
		fmt.Println("cmd run err：", err)
	}
}
